#include "sdk.h"
#include "M_Code_StyledTextCtrl.h"
#include "confirmreplacedlg.h"

BEGIN_EVENT_TABLE( ConfirmReplaceDlg, wxScrollingDialog )
  EVT_BUTTON( XRCID( "btnYes" ), ConfirmReplaceDlg::OnYes )
  EVT_BUTTON( XRCID( "btnNo" ), ConfirmReplaceDlg::OnNo )
  EVT_BUTTON( XRCID( "btnAllInFile" ), ConfirmReplaceDlg::OnAllInFile )
  EVT_BUTTON( XRCID( "btnSkipFile" ), ConfirmReplaceDlg::OnSkipFile )
  EVT_BUTTON( XRCID( "btnAll" ), ConfirmReplaceDlg::OnAll )
  EVT_BUTTON( XRCID( "btnCancel" ), ConfirmReplaceDlg::OnCancel )
END_EVENT_TABLE()

ConfirmReplaceDlg::ConfirmReplaceDlg( wxWindow* parent, bool replaceInFiles, const wxString& label ) {
  if( replaceInFiles ) {
    wxXmlResource* xml_res = wxXmlResource::Get();
    wxString resPath = ConfigManager::GetDataFolder() + _T( "/触发事件.xrc" );
    xml_res->Load( resPath );
    if( !xml_res->LoadObject( this, parent, _T( "dlgConfirmReplaceMultiple" ), _T( "wxScrollingDialog" ) ) ) {
      return;
    }
  } else {
    wxXmlResource* xml_res = wxXmlResource::Get();
    wxString resPath = ConfigManager::GetDataFolder() + _T( "/confirm_replace.xrc" );
    xml_res->Load( resPath );
    if( !xml_res->LoadObject( this, parent, _T( "dlgConfirmReplace" ), _T( "wxScrollingDialog" ) ) ) {
      return;
    }
  }
  XRCCTRL( *this, "lblMessage", wxStaticText )->SetLabel( label );
  this->SetEscapeId( XRCID( "btnCancel" ) );
}

ConfirmReplaceDlg::~ConfirmReplaceDlg() {
}

void ConfirmReplaceDlg::OnYes( wxCommandEvent& ( event ) ) {
  EndModal( crYes );
}

void ConfirmReplaceDlg::OnNo( wxCommandEvent& ( event ) ) {
  EndModal( crNo );
}

void ConfirmReplaceDlg::OnAllInFile( wxCommandEvent& ( event ) ) {
  EndModal( crAllInFile );
}

void ConfirmReplaceDlg::OnSkipFile( wxCommandEvent& ( event ) ) {
  EndModal( crSkipFile );
}

void ConfirmReplaceDlg::OnAll( wxCommandEvent& ( event ) ) {
  EndModal( crAll );
}

void ConfirmReplaceDlg::OnCancel( wxCommandEvent& ( event ) ) {
  EndModal( crCancel );
}

void ConfirmReplaceDlg::CalcPosition( M_Code_StyledTextCtrl* ed ) {
  if( !ed ) {
    return;
  }
  int w = 0, h = 0;
  GetSize( &w, &h );
  wxPoint pt = ed->PointFromPosition( ed->GetCurrentPos() );
  int ed_width = ed->GetSize().x;
  pt.x = ( ed_width - w ) / 2;
  if( pt.x < 0 ) {
    pt.x = 0;
  }
  pt = ed->ClientToScreen( pt );
  int lineHeight = ed->TextHeight( ed->GetCurrentLine() );
  int screenW = wxSystemSettings::GetMetric( wxSYS_SCREEN_X );
  int screenH = wxSystemSettings::GetMetric( wxSYS_SCREEN_Y );
  if( w > screenW ) {
    w = screenW;
  }
  if( h > screenH ) {
    h = screenH;
  }
  if( pt.x + w > screenW ) {
    pt.x = screenW - w;
  }
  if( h + 4 * lineHeight < pt.y ) {
    pt.y -= h + 4 * lineHeight;
  } else if( pt.y + lineHeight + ( 2 * h ) <= screenH ) {
    pt.y += lineHeight;
  } else {
    pt.y = 0;
  }
  SetSize( pt.x, pt.y, w, h );
}
